#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "INetAddr.hpp"


enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class UdpServer
{
public:
    UdpServer(uint16_t port)
        :_socketfd(-1), _port(port), _isrunning(false)
    {}
    void InitServer()
    {
        //1. 创建套接字
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd < 0)
        {
            LOG(FATAL, "socket create fail\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "sockrt create success, socket : %d\n", _socketfd);

        //2.0 初始化struct sockaddr_in 结构体字段
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // htonl(INADDR_ANY);

        //2.1 绑定套接字
        int n = bind(_socketfd, (const sockaddr*)&local, sizeof local);
        if(n < 0)
        {
            LOG(FATAL, "bind fail\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");


    }
    void Start()
    {
        _isrunning = true;
        while(true)
        {
            char buff[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_socketfd, buff, sizeof(buff) - 1, 0, (sockaddr*)&peer, &len);
            if(n > 0)
            {
                buff[n] = '\0';
                INetAddr addr(peer);
                LOG(INFO, "get a message from [%s : %d] %s\n", addr.IP().c_str(), addr.Port(), buff);
                sendto(_socketfd, buff, strlen(buff), 0, (const sockaddr*)&peer, len);
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {}
private:
    int _socketfd;
    uint16_t _port;
    bool _isrunning;
};